package org.ceteca.explica.server.management;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import org.ceteca.explica.core.InterfaceExplica;
import org.ceteca.explica.core.management.InterfaceManagement;
import org.ceteca.explica.core.management.ManagementManager;
import org.ceteca.explica.core.ssl.RMISSLClientSocketFactory;
import org.ceteca.explica.core.ssl.RMISSLServerSocketFactory;
import org.ceteca.explica.core.util.LoggerFactory;
import org.ceteca.explica.core.warehouse.InterfaceWarehouse;
import org.ceteca.explica.server.ServerContext;

public class ManagementManagerBuilder {
	/**
	 * Initializes the common manager remote object. Makes the registration and
	 * binding of the remote ManagementManager service.  
	 */
	public static void initManagementManager() {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
        try {
            String name = InterfaceManagement.JNDI_MANAGEMENT_MANAGER_EXPORT_NAME;
            ManagementManagerImpl manager = new ManagementManagerImpl();
            
            UnicastRemoteObject.unexportObject(manager, true);
            System.out.println("ManagementManager unexported");


            /**
             * Export the CommonManager object to listen in the assigned port
             */
            ManagementManager stub =
                (ManagementManager) UnicastRemoteObject.exportObject(manager, InterfaceManagement.RMI_MANAGEMENT_MANAGER_EXPORT_PORT, 
                		new RMISSLClientSocketFactory(),
               		 	new RMISSLServerSocketFactory());
            
            System.out.println("ManagementManager exported");

            /*
    	     * Create a registry and bind stub in registry.
    	     */
//    	    LocateRegistry.createRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    Registry registry = LocateRegistry.getRegistry(InterfaceExplica.RMI_REGISTRY_PORT);
    	    
            System.out.println("Registry located");
            registry.rebind(name, stub);
            System.out.println("ManagementManager bound");
        } catch (Exception e) {
            System.err.println("ManagementManager exception:");
            e.printStackTrace();
        }
        // Init the logger service
		System.out.println("LOGGING CONFIGURATION PATH= " + ServerContext.getInstance().getClass().getResource(InterfaceManagement.MANAGEMENT_LOG_CONFIG_FILE).getPath());
		LoggerFactory.initLogger(
				InterfaceExplica.EXPLICA_LOG_DIR,
				ServerContext.getInstance().getClass().getResourceAsStream(InterfaceManagement.MANAGEMENT_LOG_CONFIG_FILE));
	
        
        
	}
}
